import { defineStore } from "pinia";
import { AuthState } from "../interface/index";
import { loginApi } from "@/api/modules/login";
import {
  getShowMenuList,
  getFlatMenuList,
  getAllBreadcrumbList,
} from "../helper/auth";

export const useAuthStore = defineStore("auth", {
  // 存放数据
  state: (): AuthState => {
    return {
      // 按钮权限列表
      authButtonList: {},
      // 菜单权限列表
      authMenuList: [],
      // 当前页面的 router name，用来做按钮权限筛选
      routeName: "",
    };
  },
  // 修改数据（类似计算属性）
  getters: {
    // 按钮权限列表
    authButtonListGet: (state) => state.authButtonList,
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: (state) => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: (state) => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: (state) => getFlatMenuList(state.authMenuList),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: (state) => getAllBreadcrumbList(state.authMenuList),
  },
  actions: {
    // 获取按钮权限列表
    async getAuthButtonList() {
      const res = await loginApi.getButtonAuth();
      if (!res) return;
      this.authButtonList = res.data;
    },
    // 获取菜单列表
    async getAuthMenuList() {
      // this.authMenuList = menuList;
      const res = await loginApi.getMenu();
      if (!res) return;
      this.authMenuList = res.data;
    },
    // 设置当前菜单名
    async setRouteName(name: string) {
      this.routeName = name;
    },
  },
});
